package com.funquer.commons.log;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-21
 * Time: 下午5:53
 * To change this template use File | Settings | File Templates.
 *
 *
 *
 * 说明：如果需要在spring-mvc的Controller中使用到AOP，必须在Spring-mvc.xml配置<aop:aspectj-autoproxy proxy-target-class="true"/>
 * 如果需要在其他的地方使用AOP，必须把上面的配置配置在spring-X文件中才会起作用，因为他们是不同的context（上下文）
 */
@Aspect
@Component
public class LogInterceptorAspect {

    private Logger process=null;

    private Logger error=null;


    @After(value="execution(public * com.funquer..controller.*Controller.*(..))")
    public void doAfter(JoinPoint jp) {
        process=LogManager.getProcessLog(jp.getTarget().getClass());
        process.info("log Ending method: " + jp.getTarget().getClass().getName() + "."+ jp.getSignature().getName());
    }

    @Around("execution(public * com.funquer..controller.*Controller.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        process=LogManager.getProcessLog(pjp.getTarget().getClass());
        long time = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        time = System.currentTimeMillis() - time;
        process.info("process time: " + time + " ms");
        return retVal;
    }

    @Before(value="execution(public * com.funquer..controller.*Controller.*(..))")
    private void doBefore(JoinPoint jp) {
        process=LogManager.getProcessLog(jp.getTarget().getClass());
        process.info("log Begining method: "+ jp.getTarget().getClass().getName() + "."+ jp.getSignature().getName());
    }

    @AfterThrowing(value="execution(public * com.funquer..controller.*Controller.*(..))",throwing="ex")
    public void doThrowing(JoinPoint jp, Throwable ex) {
        error=LogManager.getErrorLog(jp.getTarget().getClass());
        error.error("method " + jp.getTarget().getClass().getName()+ "." + jp.getSignature().getName() + " throw exception\n"+ex.getMessage());
    }


    @AfterReturning(value="execution(public * com.funquer..controller.*Controller.*(..))",returning="reval")
    public void doAfterReturning(JoinPoint jp,String reval){
        process=LogManager.getProcessLog(jp.getTarget().getClass());
        process.info("After Returning : "+reval);
    }

}
